const Koa = require('koa')
const oauth2 = require('simple-oauth2').create(
    {
        client: {
            id: 'merryyou1',
            secret: 'merryyousecrect1'
        },
        auth: {
            authorizeHost: 'http://sso-login:8082',
            authorizePath: '/uaa/oauth/authorize',
            tokenHost : 'http://sso-login:8082',
            tokenPath: '/uaa/oauth/token'
        }
    }
)

const authorizationUri = oauth2.authorizationCode.authorizeURL({
    redirect_uri: 'http://localhost:9876',

})

const app = new Koa()

app.use(async function (ctx, next) {
    if (ctx.query.code) {
        const code = ctx.query.code

        const tokenConfig = {
            code,
            redirect_uri: 'http://localhost:9876'
        }

        const result = await oauth2.authorizationCode.getToken(tokenConfig)
        console.log(result)
        const accessToken = oauth2.accessToken.create(result)

        console.log('----')
        ctx.body = 'ok'
        console.log(accessToken)

    } else {
        ctx.redirect(authorizationUri)
    }

})

app.listen(9876)